﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Security;
using anrControls;
using Castle.MonoRail.Framework;
using StateTheaterDataModel;

namespace StateTheater.Controllers
{
	class ResourceController : SmartDispatcherController
	{
		private StateTheaterDataContext db;

		public ResourceController(StateTheaterDataContext db)
		{
			this.db = db;
		}

		public void Display(int id)
		{
			var res = db.Resources.FirstOrDefault(r => r.ResourceId == id);
			if (res == null)
			{
				// error here.
				return;
			}

			PropertyBag["Resource"] = res;
			var plays = from ru in db.ResourceUses
						where ru.ResourceID == id
						select new
						{
							Title = ru.Play.Title,
							ID = ru.PlayId
						};
			PropertyBag["Plays"] = plays.ToList();
			MembershipUser user = Membership.GetUser();
			if (user == null)
				return;
			int memberId = (int)user.ProviderUserKey;

			bool isAdmin = this.Context.CurrentUser.IsInRole("Admin");

			PropertyBag["allowEdit"] = isAdmin || db.TroupePermissions
				.Where(tp => tp.MEMBER_ID == memberId)
				.Any(tp => tp.Troupeid == res.TroupeId);
		}

		public void New()
		{
			Edit(new Resource());
			this.RenderView("Edit");
		}

		public void Edit(int id)
		{
			Edit(db.Resources.FirstOrDefault(r => r.ResourceId == id));
		}

		private void Edit(Resource resource)
		{
			throw new NotImplementedException();
		}
	}
}
